package cn.tedu.hotelApi.user.service.impl;

import cn.tedu.hotelApi.base.exception.ServiceException;
import cn.tedu.hotelApi.base.response.StatusCode;
import cn.tedu.hotelApi.base.utils.CacheUtils;
import cn.tedu.hotelApi.user.mapper.UserMapper;
import cn.tedu.hotelApi.user.pojo.dto.UserParam;
import cn.tedu.hotelApi.user.pojo.dto.UserQuery;
import cn.tedu.hotelApi.user.pojo.entity.User;
import cn.tedu.hotelApi.user.pojo.vo.UserVO;
import cn.tedu.hotelApi.user.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service("adminUserService")
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    CacheUtils cacheUtils;
    @Override
    public void saveUser(UserParam userParam) {
        User user = new User();
        BeanUtils.copyProperties(userParam, user);
        if (user.getId() == null){
            UserQuery userQuery = new UserQuery();
            userQuery.setUsername(userParam.getUsername());
            UserVO userVO = userMapper.selectUser(userQuery);
            if (userVO == null){
                user.setCreateTime(new Date());
                userMapper.insertUser(user);
            }else {
                throw new ServiceException(StatusCode.USERNAME_ALREADY_EXISTS);
            }
        }else {
            user.setUpdateTime(new Date());
            userMapper.updateUser(user);
        }
    }

    @Override
    public UserVO loginUser(UserQuery userQuery) {
        String verificationCode = userQuery.getVerificationCode();
        String captcha = cacheUtils.get("captcha").toString();
        UserVO userVO = userMapper.selectUser(userQuery);
        if (verificationCode.equalsIgnoreCase(captcha) && userQuery.getPassword().equals(userVO.getPassword())){
            cacheUtils.delete("captcha");
            return userVO;
        }else {
            cacheUtils.delete("captcha");
            throw new ServiceException(StatusCode.USERNAME_ERROR);
        }
    }
}
